//
//  EPCNetworking+Extension.swift
//  Weibo
//
//  Created by LioWu on 07/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import Foundation

extension EPCNetworking {
    
    
    /// statuses/home_timeline API
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 回调 （ [[String: AnyObject]]?, Bool ）
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion:@escaping (_ resp:[[String: AnyObject]]?, _ isSuccess:Bool)->() )  {
    
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        tokenRequest(URLString: url, parameters: params as [String : AnyObject]?, progress: nil) { (response, isSuccess) in
            
            let result = response?["statuses"] as? [[String: AnyObject]]
            
            completion(result,isSuccess)
        }
    }
    
    
    func unreadCount(completion:@escaping ((_ unreadCount: Int)->())) {
        
        guard let uid = userAccount.uid else {
            
            completion(0)
            
            return
        }
        
        let url = "https://api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: url, parameters: params as [String : AnyObject]?, progress:nil) { (response, isSuccess) in
            
            guard let dict = response as? [String: AnyObject?],
                let count = dict["status"] as? Int else {
                    
                    completion(0)
                    
                    return
            }
            
            completion(count)
        }
    }
}


// MARK: - user info
extension EPCNetworking {
    
    
    
    /// request user info
    ///
    /// - Parameter completion: block (user info dict)
    func loadUserInfo(completion:@escaping ([String: AnyObject])->()) {
        
        guard let access_token = userAccount.access_token,
            let uid = userAccount.uid else {
                
            completion([:])
            return
        }
        
        let url = "https://api.weibo.com/2/users/show.json"
        
        let params = ["access_token": access_token,
                      "uid": uid]
        
        tokenRequest(URLString: url, parameters: params as [String : AnyObject]?, progress: nil) { (response, isSuccess) in
            
            completion((response as? [String : AnyObject]) ?? [:] )
        }
    }
}

// MARK: - access_token
extension EPCNetworking {
    
    /// request access_token
    ///
    /// - Parameters:
    ///   - authCode: code
    ///   - completion: complete block (isSucess:Bool) -> ()
    func requestToken(authCode: String, completion:@escaping (_ isSucess:Bool)->()) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":EPCAppKey,
                      "client_secret":EPCAppSecret,
                      "grant_type":"authorization_code",
                      "code":authCode,
                      "redirect_uri":EPCRedirectURI]
        
        request(method: .POST, URLString: url, parameters: params as [String : AnyObject]?, progress: nil) { (response, isSuccess) in
            
            if isSuccess == false {
                completion(false)
            }
            
            self.userAccount.yy_modelSet(with: (response as? [String: AnyObject]) ?? [:])

            self.loadUserInfo(completion: { (dict) in
                
                self.userAccount.yy_modelSet(with: dict)
                
                self.userAccount.saveAccount()
                
                print(self.userAccount)
                
                completion(isSuccess)
            })
        }
    }
}
